package com.liaoyin.travel.service.back;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.liaoyin.travel.base.constant.VariableConstants;
import com.liaoyin.travel.base.service.BaseService;
import com.liaoyin.travel.bean.UserInfo;
import com.liaoyin.travel.constant.CommonConstant;
import com.liaoyin.travel.dao.BackUserMapper;
import com.liaoyin.travel.entity.BackUser;
import com.liaoyin.travel.entity.FileUpload;
import com.liaoyin.travel.entity.Users;
import com.liaoyin.travel.exception.BusinessException;
import com.liaoyin.travel.gate.JwtTokenUtil;
import com.liaoyin.travel.service.MenuService;
import com.liaoyin.travel.service.UsersService;
import com.liaoyin.travel.service.scenicInfo.LowerLevelAdminMenuService;
import com.liaoyin.travel.util.*;
import com.liaoyin.travel.view.moble.back.MenuView;
import com.liaoyin.travel.vo.UserPassWordVo;
import com.liaoyin.travel.vo.scenic.ScenicBackUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 后台用户 Service
 *
 * @author lijing
 * @date 2018/6/20 14:55
 */
@Service
public class BackUserService extends BaseService<BackUserMapper, BackUser> {

	@Autowired
	private JwtTokenUtil jwtTokenUtil;
	@Autowired
	private MenuService menuService;
	@Autowired
	private UsersService usersService;
	@Autowired
	private LowerLevelAdminMenuService lowerLevelAdminMenuService;
	
    
	/**
     * @方法名：selectBackUserList
     * @描述： 查询后台用户列表
     * @作者： rzy
     * @日期： Created in 2018/11/8 16:27
     */
	public List<BackUser> selectBackUserList(Integer num,Integer size, String userType,String nickName,String isUsing){
		UserInfo activeUser =  PartyUtil.getCurrentUserInfo();
		Optional.ofNullable(activeUser).orElseThrow(() -> new BusinessException("not.login"));
		//单位id
		String scenicId = activeUser.getScenicId();

		if (null != num && null != size){
			PageHelper.startPage(num,size);
		}
		List<BackUser> list = this.mapper.selectBackUserList(userType, nickName, isUsing,scenicId);

		if(list != null && list.size() >0) {
			FileUpload f = null;
			//用户id
			String activeUserId = activeUser.getId();
			//要删除的元素
			BackUser removeBackUser = null;
			for(BackUser b:list) {
				f = FileUploadUtil.getFileUpload(b.getId());
				if(f != null && !"".equals(f)) {
					b.setUserHeadPicUrl(CommonConstant.FILE_SERVER+f.getFilePath());
					f = null;
				}
				//删除景区管理员自己(不能够从后台管理列表编辑操作景区管理员)
				if(activeUserId.equals(b.getId())){
					removeBackUser = b;
				}
			}
			//删除景区管理员自己(不能够从后台管理列表编辑操作景区管理员)
			list.remove(removeBackUser);

		}

		return list;
	}
	
	/**
     * @方法名：insertOrUpdateBackUser
     * @描述： 新增
     * @作者： lijing
     * @日期： Created in 2018/6/20 10:27
     */
	@Transactional(rollbackFor = Exception.class)
    public void insertOrUpdateBackUser(BackUser backUser) {
      if(backUser.getId() != null && !"".equals(backUser.getId())) {

    	  if(backUser.getFileUpload() != null && !"".equals(backUser.getFileUpload())) {
        	FileUploadUtil.saveFileUpload(backUser.getFileUpload(), backUser.getId());
          }
    	  this.mapper.updateByPrimaryKeySelective(backUser);
      }else {
    	  //根据账户查询是否已经存在
          Integer isExist = this.mapper.selectByAccountCount(backUser.getAccount());
          if(isExist >0) {
        	  throw new BusinessException("user.is.isExist");
          }
    	  String id = UUIDUtil.getUUID();
    	  backUser.setId(id);
    	  backUser.setIsDelete((short)0);
    	  backUser.setCreateTime(new Date());
    	  if(backUser.getFileUpload() != null && !"".equals(backUser.getFileUpload())) {
      		FileUploadUtil.saveFileUpload(backUser.getFileUpload(), id);
      	  }
    	  backUser.setPassword(MD5Util.createPassword(ParamUtil.getValue("defaultPaword"),id));
    	  this.mapper.insertSelective(backUser);
      }
    }
    
    /**
     * @方法名：selectBackUserById
     * @描述： id查询后台用户列表
     * @作者： lijing
     * @日期： Created in 2018/6/20 10:27
     */
    public BackUser selectBackUserById(String id) {
    	if(id == null) {
    		throw new BusinessException("id.is.null","id为空");
    	}
    	BackUser b = this.mapper.selectBackUserById(id);
    	if(b != null && !"".equals(b)) {
    		FileUpload f = FileUploadUtil.getFileUpload(b.getId());
    		if(f != null && !"".equals(f)) {
    			b.setFileUpload(f);
    			f = null;
    		}
    	}
    	return b;
    }
    
    /**
     * @方法名：deleteBackUserById
     * @描述： 删除后台用户
     * @作者： lijing
     * @日期： Created in 2018/6/20 10:27
     */
    public void deleteBackUserById(String ids) {
    	if(ids == null) {
    		throw new BusinessException("id.is.null","id为空");
    	}
    	String[] id = ids.split(",");
    	this.mapper.deleteBackUserById(id);
    }
    
    /**
     * @方法名：updateUserPassWordByIdAll
     * @描述： 后台用户修改密码
     * @作者： lijing
     * @日期： Created in 2018/6/20 10:27
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer updateUserPassWordByIdAll(UserPassWordVo userPassWordVo) {
    	UserInfo user = PartyUtil.getCurrentUserInfo();
    	if(user == null) {
    		throw new BusinessException("not.login");
    	}
    	int k = 0;
    	BackUser backUser = this.mapper.selectBackUserById(user.getId());
    	if(backUser==null){
    		throw new BusinessException("user.isExist");
		}
    	if(!MD5Util.createPassword(userPassWordVo.getOldPassword(), user.getId()).equals(backUser.getPassword())){
    		throw new BusinessException("oldPassWord.is.error");
		}
    	if(userPassWordVo.getNewPassword().equals(userPassWordVo.getReplayPassword())) {
    		/*if(userPassWordVo.getNewPassword().length() <15) {*/
    			if(MD5Util.createPassword(userPassWordVo.getOldPassword(),user.getId()).equals(user.getPassword())) {
    				BackUser b = new BackUser();
    				b.setId(user.getId());
    				if(userPassWordVo.getNewUserName()!= null && !"".equals(userPassWordVo.getNewUserName())) {
    					b.setAccount(userPassWordVo.getNewUserName());
    				}
    				b.setPassword(MD5Util.createPassword(userPassWordVo.getNewPassword(), user.getId()));
    				b.setNickName(userPassWordVo.getNickName());
    				this.mapper.updateByPrimaryKeySelective(b);
    				k = 1;
    			}else {
    				k = 2;
    			}
    		/*}else {
    			k = 4;
    		}*/
    	}
    	return k;
    }
    /**
     * @方法名：selectThisByUserName
     * @描述： 根据account后台用户
     * @作者： lijing
     * @日期： Created in 2018/6/20 10:27
     */
    public Integer selectThisByUserName(String account) {
    	if(account == null) {
    		throw new BusinessException("account.is.null");
    	}
    	int k = this.mapper.selectByAccountCount(account);
    	return k;
    }
    
    /**
     * @方法名：selectThisByBusniId
     * @描述： 根据商家id查询后台用户
     * @作者： lijing
     * @日期： Created in 2018/6/20 10:27
     */
    public BackUser selectThisByBusniId(String id) {
    
    	return this.mapper.selectThisByBusniId(id);
    }
    
    
    /**
     * @方法名：logout
     * @描述： 退出
     * @作者： lijing
     * @日期： Created in 2018/6/20 10:27
     */
    public void logout() {
    	UserInfo user = PartyUtil.getCurrentUserInfo();
    	if(user == null) {
    		return;
    	}
    	RedisUtil.del(user.getAccount()+"#"+user.getId());
    }
    
    /**
     * @方法名：resetPassword
     * @描述： 重置密码
     * @作者： lijing
     * @日期： Created in 2018/6/20 10:27
     */
    public void resetPassword(String id) {
    	if(id == null) {
    		throw new BusinessException("id.is.null","id为空");
    	}
    	String pass = "e10adc3949ba59abbe56e057f20f883e";
    	BackUser b = this.mapper.selectByPrimaryKey(id);
    	b.setPassword(MD5Util.createPassword(pass, b.getId()));
    	this.mapper.updateByPrimaryKeySelective(b);
    }
    /** 
    * @Description: 后台账号密码登录 
    * @Author: rzy 
    * @Date: 2018/11/28 
    */
    public UserInfo loginByPassword(String account, String password){
    	if(account == null) {
    		throw new BusinessException("phone.is.null");
    	}
    	if(password == null) {
    		throw new BusinessException("password.is.null");
    	}
		UserInfo user = this.mapper.selectBackUserAccount(account);
		if (user==null || !"1".equals(user.getIsUsing())){
			throw new BusinessException("user.isExist");
		}

		if (user.getPassword().equals(MD5Util.createPassword(password,user.getId()))){
            System.err.println("password="+password);
			//头像地址
			FileUpload f = FileUploadUtil.getFileUpload(user.getId());
			if (f!=null){
				user.setUserHeadPicUrl(CommonConstant.FILE_SERVER+f.getFilePath());
				f= null;
			}
			//权限菜单

			//生成token
			//String token = jwtTokenUtil.generateToken(dbuser.getAccount());
			String token = JwtTokenUtil.createJWT(user.getAccount(),user.getId(),user.getNickName(),null,null,null,24*24*60*60*1000,"123456");
			user.setToken(token);
			//将用户信息保存到redis
			RedisUtil.set(user.getAccount() + "#" + user.getId(), JsonUtil.getJsonString(user), jwtTokenUtil.getExpiration());
		}else{
			throw new BusinessException("password.is.error");
		}
		//获取权限菜单
		List<MenuView> menuList=null;
		//角色id
		String roleId = user.getRoleId();
		if(roleId.equals(VariableConstants.STRING_CONSTANT_4)){
			//单位(景区)子管理员
			menuList=menuService.selectScenicLowerLevelAdminMenuByUserId(user.getId());
		}else{
			menuList=menuService.selectMenuByUserId(user.getId());
		}

	    System.err.println("------------- 权限菜单 -------------");
	    System.err.println(JSON.toJSON(menuList));
		if(menuList.size()==0){
			throw new BusinessException("unassigned.menu");
		}
		user.setMenuList(menuList);
		return user;
	}
	/**
	* @Description 绑定企业用户
	* @Author  rzy
	* @date 2018/12/17 18:43
	*/
	public void bindEnterpriseUsers(String userId){
		UserInfo user = PartyUtil.getCurrentUserInfo();
		if(user == null) {
			throw new BusinessException("user.is.null","用户未登录或登录超时");
		}
		if (userId==null || "".equals(userId)){
			throw new BusinessException("id.is.null");
		}
		Users users = usersService.selectUsersById(userId);
		if (user==null){
			throw new BusinessException("user.isExist");
		}
		BackUser bu = this.selectBackUserById(user.getId());
		if (bu==null){
			throw new BusinessException("user.is.null","用户未登录或登录超时");
		}
		bu.setBusinessId(users.getId());
		this.mapper.updateByPrimaryKeySelective(bu);
		users=null;
	}

	/**
	* @Description 取消绑定
	* @Author  rzy
	* @date 2018/12/18 10:21
	*/
	public void cancelTheBinding(){
		UserInfo user = PartyUtil.getCurrentUserInfo();
		if(user == null) {
			throw new BusinessException("user.is.null","用户未登录或登录超时");
		}
		BackUser bu = this.selectBackUserById(user.getId());
		if (bu==null){
			throw new BusinessException("user.isExist");
		}
		bu.setBusinessId("");
		this.updateSelectiveById(bu);

	}


	/**
	 * @方法名：selectBackUserByPhone
	 * @描述： 通过电话查询后台管理用户信息
	 * @作者： Kuang.JiaZhuo
	 * @日期： Created in 2020/2/21 15:25
	 */
	public List<BackUser> selectBackUserByPhone(String phone) {
		List<BackUser> list = this.mapper.selectBackUserByPhone(phone);
		return list;
	}

	/**
	 * @方法名：selectBackUserByAccount
	 * @描述： 通过账号查询后台用户
	 * @作者： Kuang.JiaZhuo
	 * @日期： Created in 2020/2/21 16:19
	 */
	public List<BackUser> selectBackUserByAccount(String account) {
		List<BackUser> list = this.mapper.selectBackUserByAccount(account);
		return list;
	}

	/**
	 * @方法名：selectBackUserByAccountOrPhone
	 * @描述： 根据账号或联系电话查询后台用户
	 * @作者： Kuang.JiaZhuo
	 * @日期： Created in 2020/2/21 18:44
	 */
	public List<BackUser> selectBackUserByAccountOrPhone(String account, String phone) {
		List<BackUser> list = this.mapper.selectBackUserByAccountOrPhone(account,phone);
		return list;
	}

	/**
	 * @方法名：selectBackUserByIdentityCard
	 * @描述： 根据身份证号查询后台用户信息
	 * @作者： kjz
	 * @日期： Created in 2020/2/24 17:41
	 */
    public List<BackUser> selectBackUserByIdentityCard(String identityCard, String scenicId) {
    	return this.mapper.selectBackUserByIdentityCard(identityCard,scenicId);
    }

    /**
     * @方法名：insertOrUpdateScenicBackUser
     * @描述： 单位总管理员新增或修改单位(景区或机构)子管理员
     * @作者： kjz
     * @日期： Created in 2020/4/28 14:57
     */
	@Transactional(rollbackFor = Exception.class)
	public int insertOrUpdateScenicBackUser(ScenicBackUserVo scenicBackUserVo) {
		//获取当前登录管理员的用户信息
		UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
		Optional.ofNullable(curveUserInfo).orElseThrow(() -> new BusinessException("not.login"));
		/** 景区id */
		String scenicId = curveUserInfo.getScenicId();

		String id = scenicBackUserVo.getId();
		//账户
		String account = scenicBackUserVo.getAccount();
		//昵称
		String nickName = scenicBackUserVo.getNickName();
		//头像文件实体
		FileUpload headPortraitFile = scenicBackUserVo.getHeadPortraitFile();

		BackUser backUser = new BackUser()
				.setAccount(account)
				.setNickName(nickName)
				.setIsUsing(scenicBackUserVo.getIsUsing());
		//返回结果
		int result = 0;

		if(null==id || "".equals(id)){
			/** 新增 */
			//判断账户是否重复
			judgeAccountIsReDo(account,null);
			//生成id
			id = SnowIdUtil.getInstance().nextId();

			//当前登录管理员的账号类型
			String accountType = curveUserInfo.getAccountType();

			if(accountType.equals(VariableConstants.STRING_CONSTANT_1)){
				//当前是景区管理员登录
				backUser.setAccountType(VariableConstants.STRING_CONSTANT_1);
			}else if(accountType.equals(VariableConstants.STRING_CONSTANT_2)){
				//当前是机构管理员登录
				backUser.setAccountType(VariableConstants.STRING_CONSTANT_2);
				backUser.setOrganType(curveUserInfo.getOrganType());
			}

			backUser.setId(id).setScenicId(scenicId)
					.setCreateTime(new Date())
					.setPassword(MD5Util.createPassword(ParamUtil.getValue("defaultPaword"),id))
					//单位子管理员的角色关联
					.setRoleId(VariableConstants.STRING_CONSTANT_4)
					.setIsDelete((short) 0);

			result = this.mapper.insert(backUser);

		}else{
			/** 更新 */
			//判断账户是否重复
			judgeAccountIsReDo(account,id);
			backUser.setId(id);
			result = this.mapper.updateByPrimaryKeySelective(backUser);
		}

		/** 传了头像，就写入数据库 */
		if(headPortraitFile != null ) {
			FileUploadUtil.saveFileUpload(headPortraitFile,id);
		}


		return result;

	}

	/**
	 * @方法名：judgeAccountIsReDo
	 * @描述： 判断账户是否重复,若重复抛出异常
	 * @作者： kjz
	 * @日期： Created in 2020/4/28 15:07
	 */
	public void judgeAccountIsReDo(String account, String id) {
		List<BackUser> backUsers = this.mapper.selectBackUserByAccountAndId(account,id);
		if (backUsers.size() > 0) {
			throw new BusinessException("account.is.exist");
		}
	}

	/**
	 * @方法名：selectNickNameById
	 * @描述： 根据后台用户id查询后台用户昵称
	 * @作者： kjz
	 * @日期： Created in 2020/8/10 19:21
	 */
	public String selectNickNameById(String userId) {
		return mapper.selectNickNameById(userId);
	}
}
